import React, {Component} from 'react';
import {Table,Button,Card,message,Modal,Form, Input,Select} from 'antd';
import {reqUserList,reqAddUser,reqUpdateUser,reqDeleteUser} from '../../api/index.js'
import dayjs from 'dayjs'

import {QuestionCircleOutlined} from '@ant-design/icons'

const { confirm } = Modal;

class User extends Component {
  state = {
    userList: [],  // 所有用户列表
    roles: [],   // 角色列表
    userVisible: false,  // 添加/修改 用户modal框显示隐藏
    updateUserInfo: '',  // 修改用户
  }
  userForm = React.createRef()
  render() {
    let {userList,userVisible,roles,updateUserInfo} = this.state
    // table表格配置
    const columns = [
      {
        title: '用户名',
        dataIndex: 'username',
        key: 'username',
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        key: 'email',
      },
      {
        title: '电话',
        dataIndex: 'phone',
        key: 'phone',
      },
      {
        title: '注册时间',
        dataIndex: 'create_time',
        key: 'create_time',
        render: time => dayjs(time).format('YYYY-MM-DD HH:mm:ss')
      },
      {
        title: '所属角色',
        dataIndex: 'role_id',
        key: 'role_id',
        render: roleId => {
          let roles = this.state.roles
          let item = roles.find(item => {
            return item._id === roleId
          })
          return  item.name
        }
      },
      {
        title: '操作',
        render: (item)=>{
          return <div>
            <Button type="link" onClick={this.showUserModal.bind(this, item)}>修改</Button>
            <Button type="link" onClick={this.deleteUser.bind(this, item)}>删除</Button>
          </div>
        }
      },
    ];
    return <div>
      <Card title={<Button onClick={this.showUserModal.bind(this, null)} type="primary">创建用户</Button>}>
        <Table dataSource={userList} columns={columns} bordered rowKey="_id"/>;
      </Card>
  
      {/* 添加/修改 用户modal框 */}
      <Modal
        title="添加用户"
        visible={userVisible}
        onOk={this.handleUserOk}
        onCancel={this.handleUserCancel}
        forceRender
      >
        <Form
          labelCol={{span: 4}}
          ref={this.userForm}
        >
          <Form.Item
            label="用户名："
            name="username"
            rules={[{required: true, message: '必须输入用户名!'}]}
          >
            <Input placeholder="请输入用户名"/>
          </Form.Item>
          <Form.Item
            label="密码："
            name="password"
            rules={[{required: true, message: '必须输入密码!'}]}
            hidden={updateUserInfo?true:false}
          >
            <Input placeholder="请输入密码"/>
          </Form.Item>
          <Form.Item
            label="手机号："
            name="phone"
            rules={[{required: true, message: '必须输入手机号!'}]}
          >
            <Input placeholder="请输入手机号"/>
          </Form.Item>
          <Form.Item
            label="邮箱："
            name="email"
            rules={[{required: true, message: '必须输入邮箱!'}]}
          >
            <Input placeholder="请输入邮箱"/>
          </Form.Item>
          <Form.Item
            label="角色"
            name="role_id"
            rules={[{required: true, message: '必须选择角色!'}]}
          >
            <Select placeholder="请选择分类">
              {roles.map(item => {
                return <Select.Option key={item._id} value={item._id}>{item.name}</Select.Option>
              })}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  }
  
  componentDidMount() {
    // 获取所有用户列表
    this.getUserList()
  }
  
  // 获取所有用户列表
  getUserList = async () => {
    let res = await reqUserList()
    let {status,data,msg} = res
    if (status === 0) {  //获取成功
      this.setState({
        userList: data.users,
        roles: data.roles
      })
    } else {  //获取失败
      message.error(msg, 1)
    }
  };
  
  // 添加/修改 用户modal
  showUserModal = (item) => {
    if (item) {  // 修改页面
      this.setState({
        userVisible: true,
        updateUserInfo:item
      },()=>{
        // 设置表单值
        this.userForm.current.setFieldsValue({
          username:item.username,
          phone:item.phone,
          email:item.email,
          role_id:item.role_id,
          password: item.password
        })
      });
      
    } else {  // 添加页面
      this.setState({
        userVisible: true,
      });
    }
  };
  
  // 添加用户
  addUser = () => {
    this.userForm.current.validateFields()
      .then(async value => {
        let res = await reqAddUser(value)
        let {status,msg} = res
        if (status === 0) {
          message.success('添加用户成功！',1)
          this.setState({
            addUserVisible: false,
          });
          // 重新获取所有用户列表
          this.getUserList()
  
          // 重置表单到 initialValues
          this.userForm.current.resetFields()
  
          this.setState({
            userVisible: false,  // 隐藏model，清空值
          })
        } else {
          message.error(msg,1)
        }
      })
      .catch(errorInfo => {
        message.error(errorInfo.errorFields[0].errors[0])
      })
  }
  
  // 修改用户
  updateUser = () => {
    let {updateUserInfo} = this.state
    let userList = [...this.state.userList]
    this.userForm.current.validateFields()
      .then(async values => {
        let res = await reqUpdateUser({_id:updateUserInfo._id,...values})
        let {data,status,msg} = res
        if (status === 0) {  // 请求成功
          message.success('更新用户成功！',1)
          userList.forEach((item,i) => {
            if (item._id === data._id){
              return userList.splice(i,1,data)
            }
          })
          this.setState({
            userList,
            userVisible: false,  // 隐藏model，清空值
            updateUserInfo: ''
          })
          
          // 重置表单到 initialValues
          this.userForm.current.resetFields()
        } else { // 请求失败
          message.error(msg,1)
        }
        
      })
      .catch(errorInfo=>{
        console.log(errorInfo)
      })
  }
  
  // 添加/修改 用户modal点击ok
  handleUserOk = () => {
    let {updateUserInfo} = this.state
    if (updateUserInfo) {   // 修改用户
       this.updateUser()
    } else {   // 添加用户
      this.addUser()
    }
  };
  
  // 添加/修改 用户modal点击cancel
  handleUserCancel = () => {
    this.setState({
      userVisible: false,
      updateUserInfo: ''
    });
    
    // 重置表单到 initialValues
    this.userForm.current.resetFields()
  };
  
  deleteUser = (item) => {
    let userList = [...this.state.userList]
    confirm({
      icon: <QuestionCircleOutlined />,
      content: `确定删除${item.username}吗？`,
      onOk: async () => {
        let res = await reqDeleteUser({userId:item._id})
        let {status,msg} = res
        if (status === 0) {
          message.success('删除用户成功！',1)
          userList.forEach((user,i)=>{
            if (user._id === item._id){
              return userList.splice(i,1)
            }
          })
          this.setState({
            userList
          })
        } else {
          message.error(msg,1)
        }
      }
    });
  }
  
}

export default User;
